import { createRouter, createWebHashHistory } from 'vue-router'
import login from '@/views/login.vue'
import index from '../views/index'
import AddCustomer from '../views/AddCustomer.vue'
import ListCustomer from "@/views/ListCustomer";
import { isLoggedIn } from '../utils/auth';

const routes = [
  {/*为默认访问路径*/
    path: '/',
    name: 'login',
    component: login
  },
  {
    path: '/index',
    name: 'index',
    component: index,
    meta: { requiresAuth: true }
  },
  {
    path: '/AddCustomer',
    name: 'AddCustomer',
    component: AddCustomer,
    meta: { requiresAuth: true }
  },
  {
    path: '/ListCustomer',
    name: 'ListCustomer',
    component: ListCustomer,
    meta: { requiresAuth: true }
  }

]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 检查路由是否需要认证
  if (to.meta.requiresAuth) {
    // 检查用户是否已登录
    if (!isLoggedIn()) {
      // 未登录，重定向到登录页
      next('/');
    } else {
      // 已登录，允许访问
      next();
    }
  } else {
    // 不需要认证的路由，直接允许访问
    next();
  }
});

export default router
